package DualRMI;

import java.net.InetAddress;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class Client {
	Registry registry;
	RemoteInterface serverRIObject;
	RemoteInterface myRIObject;
	int myPort;
	
	public Client(InetAddress address, int port, int myPort){
		connect2Server(address, port);
		myRIObject = new RemoteObject("test");
		try {
			System.out.println("Trying to place a object on registry");
			RemoteInterface stub = (RemoteInterface) UnicastRemoteObject.exportObject(myRIObject, myPort);
			
			registry.rebind(myRIObject.myId(), stub);
			System.out.println("Successfully placed an object on registry");
		} catch (RemoteException e) {
			System.out.println("Could not place object on registry");
			e.printStackTrace();
		}
		try {
			System.out.println("Trying to contact server");
			serverRIObject.fetchMe("test", registry);
			System.out.println("Contact was made");
		} catch (RemoteException e) {
			System.out.println("The server did not catch it");
			e.printStackTrace();
		}
		
	}
	
	public RemoteInterface getRIObject(){
		return serverRIObject;
	}
	
	private void connect2Server(InetAddress address, int port){
		try {
			connect2ServerLogic(address, port);
		} catch (RemoteException e) {
			System.out.println("Wrong host maybe?");
			e.printStackTrace();
		} 
	
	}
	private void connect2ServerLogic(InetAddress address, int port) throws RemoteException{
		System.out.println("Trying to connect to "+address.getHostAddress()+":"+port);
		registry = LocateRegistry.getRegistry(address.getHostAddress(), port);
		System.out.println("Registry located.");
		serverRIObject = (RemoteInterface) RemoteObject.lookupRIObject("serverObj", registry);
		System.out.println("Server Object Located");
	}
}
